//
//  AppConfig.swift
//  PPApp
//
//  Created by xiaopin on 2024/2/28.
//

import Toast_Swift

/*
 应用程序个性化私有配置
 */

//MARK: 基础配置信息
let DefaultLanguage = LanguageType.zh_Hans.rawValue
/* 分页大小 */
let PageSize = 20
/* CoreData */
let CoreDataModelName = "Model"

/* App 基础配置 */
//网站加密秘钥
let OSSKey = "sQhc_W-.b17*!ken"
let WebAppKey = "Dds#SDafu23!4R5SDFS8*2"

let AppleID = "1591567419"
let AppStoreInfoUrl = "http://itunes.apple.com/lookup?id=\(AppleID)"
let AppStoreDownUrl = "https://apps.apple.com/app/id\(AppleID)"

/// 开启调试模式
var OpenDebug:Bool = false
/// 是否禁用HTTP代理拦截
let DisableHTTPProxy:Bool = false
/// 是否显示请求的返回结果
let SHOW_API_RESPONSE_LOG = true
/// 是否显示自定义日志
let SHOW_CUSTOM_LOG:Bool = true
/// 是否显示SOCKET日志
let SHOW_SOCKET_LOG:Bool = true

//MARK: 第三方平台信息配置
//正式第三方
let AppKey_UMeng = "614410d62a91a03cef4b0d44"

let AppKey_ShareSDK = "2c11ae0d93560"
let AppSecret_ShareSDK = "eda73f9696a36836c8fb84579b259280"

let AppKey_weixin = ""
let AppSecret_weixin = ""
let AppKey_weibo = ""
let AppSecret_weibo = ""
//QQ转16进制方法：echo 'ibase=10;obase=16;101887408' |bc   -> QQ0612ADB0
let AppKey_QQ = ""
let AppSecret_QQ = ""

let AppKey_Ali = ""

//MARK: 全局公共方法
/// 导航栏背景图：渐变颜色
/// - Returns: <#description#>
func navBackImageDefault() -> UIImage?{
    return UIImage.gradientImage(CGSize(width: pp_screen_width, height: pp_screen_navbar_height), Color_Main1, Color_Main2)
}

/// 导航栏背景图：单颜色
/// - Parameter color: <#color description#>
/// - Returns: <#description#>
func navBackImageWithColor(_ color:UIColor) -> UIImage?{
    return UIImage.colorImage(CGSize(width: pp_screen_width, height: pp_screen_navbar_height), color)
}

/// 是否SH
/// - Returns: <#description#>
func isSH() -> Bool{
    if appConfig()?.shStatus == true {
        if appConfig()?.shVer == pp_AppVersion {
            return true
        }
    }
    return false
}

/// 网络是否正常连接
/// - Returns: <#description#>
func isNetworkConnected() -> Bool{
    var isConnected = false
    switch XPApplication.shared.netEnv {
    case .wifi,.cellular:
        isConnected = true
    default:
        break
    }
    return isConnected
}

/// 是否登录
/// - Returns: <#description#>
func isLogined() -> Bool{
    return XPApplication.shared.isLogined
}

/// 当前应用配置信息
/// - Returns: <#description#>
func appConfig() -> XPAppConfig?{
    return XPApplication.shared.appConfig
}


/// 当前登录用户ID
/// - Returns: <#description#>
func currentUserId() -> Int{
    var userId = 0
    if XPApplication.shared.isLogined {
        if let user = XPApplication.shared.loginUser {
            userId = user.user_id
        }
    }
    return userId
}

/// 当前登录用户
/// - Returns: <#description#>
func currentUser() -> XPBaseUser?{
    if XPApplication.shared.isLogined {
        if let user = XPApplication.shared.loginUser {
            return user
        }
    }
    return nil
}

/// 当前语言Code
func currentLangCode() -> String{
//    var code = XPApplication.shared.language
//    code = code == "en" ? "en-US" : code
//    guard let languages = XPApplication.shared.languages else {
//        return "en-US"}
//    if languages.contains(where: {return $0.language_code == code}){
//        return code
//    }
    return "en-US"
}

/// 当前登录用户角色
/// - Returns: <#description#>
func UserRole() -> Int{
    return 0
}
/// 当前用户Token或者游客Token
func currentToken() -> String{
    if let user = XPApplication.shared.loginUser {
        return user.token ?? ""
    }
    return ""
}

/// 当前主题样式
/// - Returns: <#description#>
func currentThemeMode() -> ThemeMode{
    return XPApplication.shared.themeMode
}

/// 显示提示消息
/// - Parameter message: <#message description#>
func showAlert(_ message:String?) {
    DispatchQueue.main.async {
        guard let msg = message else { return }
        
        var style = ToastStyle()
        style.backgroundColor = pp_color(#colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.8), #colorLiteral(red: 0.1529411765, green: 0.1529411765, blue: 0.1882352941, alpha: 1))
        style.messageColor = pp_color(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), #colorLiteral(red: 0.6352941176, green: 0.6352941176, blue: 0.6470588235, alpha: 1))
        pp_keyWindow()?.makeToast(msg.localized, duration: 2.0, position: .center, title: nil, image: nil, style: style, completion: { (didTap) in
            
        })
    }
}
/// 显示提示消息(调试时显示)
/// - Parameter message: <#message description#>
func showAlertDebug(_ message:String?) {
    DispatchQueue.main.async {
        guard let msg = message else { return }
        #if DEBUG
        var style = ToastStyle()
        style.backgroundColor = pp_color(#colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.8), #colorLiteral(red: 0.1529411765, green: 0.1529411765, blue: 0.1882352941, alpha: 1))
        style.messageColor = pp_color(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), #colorLiteral(red: 0.6352941176, green: 0.6352941176, blue: 0.6470588235, alpha: 1))
        pp_keyWindow()?.makeToast(msg.localized, duration: 2.0, position: .center, title: nil, image: nil, style: style, completion: { (didTap) in
            
        })
        #endif
    }
}

/// 弹出系统弹窗提示
/// - Parameters:
///   - target: 控制器
///   - title: 标题
///   - message: 消息内容
func showAlertVC(_ target:UIViewController?,_ title:String? = nil, _ message:String? = nil, okAction: ((UIAlertAction)->())? = nil){
    DispatchQueue.main.async {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "MT_OK".localized, style: .default, handler: okAction))
        target?.present(alert, animated: true, completion: nil)
    }
}

/// 显示错误提示消息
/// - Parameter message: <#message description#>
func showError(_ message:String?) {
    guard let msg = message else { return }
    DispatchQueue.main.async {
        var style = ToastStyle()
        style.backgroundColor = pp_color(#colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.8), #colorLiteral(red: 0.1529411765, green: 0.1529411765, blue: 0.1882352941, alpha: 1))
        style.messageColor = pp_color(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), #colorLiteral(red: 0.6352941176, green: 0.6352941176, blue: 0.6470588235, alpha: 1))
        pp_keyWindow()?.makeToast(msg.localized, duration: 2.0, position: .center, title: nil, image: nil, style: style, completion: { (didTap) in
            
        })
    }
}

/// 友盟统计分析事件记录
/// - Parameters:
///   - event: 事件名
///   - parameters: 参数
func umengLogEvent(_ event:String, label:String = ""){
    if kRunEnv == .release{
        if label.isEmpty {
            //UMAnalyticsSwift.event(eventId: event)
        }else{
            //UMAnalyticsSwift.event(eventId: event, label: label)
        }
    }
}

/// Firebase统计分析事件记录
/// - Parameters:
///   - event: 事件名
///   - parameters: 参数
func firebaseLogEvent(_ event:String, _ parameters:[String:Any] = [:]){
    if kRunEnv == .release{
        //Analytics.logEvent(event, parameters: parameters)
    }
}

//MARK: 图片网络地址格式化

/// 判断URL是不是一个公司文件服务器的图片地址
/// - Parameter urlStr: <#urlStr description#>
/// - Returns: <#description#>
func image_format_check(_ urlStr:String) -> Bool{
    let url = URL(string: urlStr)
    if url?.host?.contains(find: kFileHost) == true && (url?.pathExtension == "jpg" || url?.pathExtension == "jpeg" || url?.pathExtension == "png"){
        return true
    }
    return false
}

/// 单边等比缩放，通过宽度等比缩放
/// - Parameters:
///   - urlStr: 原图地址
///   - width: 缩放宽度
/// - Returns: 返回格式化后的图片地址
func image_format_resizebywidth(_ urlStr:String?,_ width:CGFloat = 0) -> String?{
    guard let url = urlStr else {return nil}
    if width <= 0 {return url}
    if !image_format_check(url) {return url}
    guard let config = appConfig() else{ return url }
    guard let imageParam = config.imageParam else{ return url }
    //如果有配置信息、有图片参数信息、宽度>0、是一个图片的url地址，是siwei.com域名下，都符合要求追加参数
    let newUrl = url + imageParam.resize_byWidth.replacingOccurrences(of: "[W]", with: "\(width.i*2)")
    return newUrl
}

/// 固定宽高，自动裁剪，将图自动裁剪成宽度为[W]px，高度为[H]px 的效果图, 横向竖向取中间部分
/// - Parameters:
///   - urlStr: 原图地址
///   - width: 固定宽度
///   - height: 固定高度
/// - Returns: 返回格式化后的图片地址
func image_format_resizebyfillwh(_ urlStr:String?,_ width:CGFloat = 0,_ height:CGFloat = 0) -> String?{
    guard let url = urlStr else {return nil}
    if width <= 0 {return url}
    let tHeight = height == 0 ? width : height
    if !image_format_check(url) {return url}
    guard let config = appConfig() else{ return url }
    guard let imageParam = config.imageParam else{ return url }
    //如果有配置信息、有图片参数信息、宽度>0、是一个图片的url地址，是siwei.com域名下，都符合要求追加参数
    let newUrl = url + imageParam.resize_byFillWH.replacingOccurrences(of: "[W]", with: "\(width.i*2)").replacingOccurrences(of: "[H]", with: "\(tHeight.i*2)")
    return newUrl
}

/// 按比例缩放 ,倍数百分比。小于100为缩小，大于100为放大
/// - Parameters:
///   - urlStr: 原图地址
///   - proportion: 比例。小于100为缩小，大于100为放大
/// - Returns: 返回格式化后的图片地址
func image_format_resizebyscale(_ urlStr:String?,_ proportion:Int = 0) -> String?{
    guard let url = urlStr else {return nil}
    if !image_format_check(url) {return url}
    guard let config = appConfig() else{ return url }
    guard let imageParam = config.imageParam else{ return url }
    //如果有配置信息、有图片参数信息、宽度>0、是一个图片的url地址，是siwei.com域名下，都符合要求追加参数
    let newUrl = url + imageParam.resize_byScale.replacingOccurrences(of: "[P]", with: "\(proportion)")
    return newUrl
}

/// 圆图，非圆角部分透明，[R]为半径
/// - Parameters:
///   - urlStr: 原图地址
///   - radius: 半径
/// - Returns: 返回格式化后的图片地址
func image_format_circle(_ urlStr:String?,_ radius:Int = 0) -> String?{
    guard let url = urlStr else {return nil}
    if radius <= 0 {return url}
    if !image_format_check(url) {return url}
    guard let config = appConfig() else{ return url }
    guard let imageParam = config.imageParam else{ return url }
    //如果有配置信息、有图片参数信息、宽度>0、是一个图片的url地址，是siwei.com域名下，都符合要求追加参数
    let newUrl = url + imageParam.circle.replacingOccurrences(of: "[R]", with: "\(radius)")
    return newUrl
}

/// 将图片缩略为宽度[W]，并且进行模糊半径为[R]，标准差为[S]的模糊处理。
/// - Parameters:
///   - urlStr: 原图地址
///   - width: 缩略宽度
///   - radius: 模糊半径
///   - standardDeviation: 标准差
/// - Returns: 返回格式化后的图片地址
func image_format_blur(_ urlStr:String?, _ width:CGFloat = 0,_ radius:Int = 3,_ standardDeviation:Int = 2) -> String?{
    guard let url = urlStr else {return nil}
    if width <= 0 {return url}
    if !image_format_check(url) {return url}
    guard let config = appConfig() else{ return url }
    guard let imageParam = config.imageParam else{ return url }

    //如果有配置信息、有图片参数信息、宽度>0、是一个图片的url地址，是siwei.com域名下，都符合要求追加参数
    let newUrl = url + imageParam.blur.replacingOccurrences(of: "[W]", with: "\(width.i*2)").replacingOccurrences(of: "[R]", with: "\(radius)").replacingOccurrences(of: "[S]", with: "\(standardDeviation)")
    return newUrl
}

/// 将图片缩略成宽度是[W], 并且保存成渐进显示的 jpg 格式。
/// - Parameters:
///   - urlStr: 原图地址
///   - width: 宽度
/// - Returns: 返回格式化后的图片地址
func image_format_interlace(_ urlStr:String?, _ width:CGFloat = 0) -> String?{
    guard let url = urlStr else {return nil}
    if width <= 0 {return url}
    if !image_format_check(url) {return url}
    guard let config = appConfig() else{ return url }
    guard let imageParam = config.imageParam else{ return urlStr }
    //如果有配置信息、有图片参数信息、宽度>0、是一个图片的url地址，是siwei.com域名下，都符合要求追加参数
    let newUrl = url + imageParam.interlace.replacingOccurrences(of: "[W]", with: "\(width.i*2)")
    return newUrl
}

//MARK: 应用归档缓存Key
/// 基础信息配置文件
let mtArchiveKey_AppConifg = "mtArchive_AppConifg.archive"
/// 语言包信息
let mtArchiveKey_Languages = "mtArchiveKey_Languages.archive"
/// 资讯频道缓存
let mtArchiveKey_NewsChannels = "mtArchiveKey_NewsChannels.archive"
/// 频道资讯详情
let mtArchiveKey_NewsDetail = "mtArchive_News_Detail_[id].archive"
 
//MARK: 常用枚举

//MARK: >>字体
/*
 //查看所有字体的名称方法
 for fontfamilyname in UIFont.familyNames {
     for name in UIFont.fontNames(forFamilyName: fontfamilyname) {
         PPLog(name)
     }
 }
 **/
enum AppFont:String {
    /// 常规体
    case `default` = "HelveticaNeue"
    /// 斜体
    case HN_Italic = "HelveticaNeue-Italic"
    /// 超细体
    case HN_UltraLight = "HelveticaNeue-UltraLight"
    /// 超细斜体
    case HN_UltraLightItalic = "HelveticaNeue-UltraLightItalic"
    /// 瘦体
    case HN_Thin = "HelveticaNeue-Thin"
    /// 瘦斜体
    case HN_ThinItalic = "HelveticaNeue-ThinItalic"
    /// 细体
    case HN_Light = "HelveticaNeue-Light"
    /// 细斜体
    case HN_LightItalic = "HelveticaNeue-LightItalic"
    /// 中等
    case HN_Medium = "HelveticaNeue-Medium"
    /// 中等斜体
    case HN_MediumItalic = "HelveticaNeue-MediumItalic"
    /// 粗体
    case HN_Bold = "HelveticaNeue-Bold"
    /// 粗斜体
    case HN_BoldItalic = "HelveticaNeue-BoldItalic"
    /// 紧缩粗体
    case HN_CondensedBold = "HelveticaNeue-CondensedBold"
    /// 紧缩黑体
    case HN_CondensedBlack = "HelveticaNeue-CondensedBlack"
}

func pp_font(_ fontName:AppFont, _ fontSize:CGFloat) -> UIFont{
    return UIFont(name: fontName.rawValue, size: fontSize)!
}

